const { Connection, PublicKey } = require('@solana/web3.js');
const { getAssociatedTokenAddress, getAccount } = require('@solana/spl-token');

// 配置 - 使用您的实际代币地址
const CONFIG = {
  tokenAddress: '4C5SJj6Gfd86jTS7PgtYmjGjGxrG9GAuLUmQ47vGnQPc', // 您修复后的代币
  userAddress: 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac',  // 您的地址
  apiUrl: 'http://localhost:7172',
  rpcUrl: 'https://api.devnet.solana.com'
};

const connection = new Connection(CONFIG.rpcUrl, 'confirmed');

// 检查代币信息
async function checkTokenInfo() {
  console.log('🔍 检查代币信息...');
  
  try {
    const tokenMint = new PublicKey(CONFIG.tokenAddress);
    const mintInfo = await connection.getParsedAccountInfo(tokenMint);
    
    if (mintInfo.value && mintInfo.value.data && mintInfo.value.data.parsed) {
      const { decimals, supply } = mintInfo.value.data.parsed.info;
      const actualSupply = Number(supply) / Math.pow(10, decimals);
      
      console.log(`✅ 代币供应量: ${actualSupply.toLocaleString()} 个代币`);
      console.log(`📊 小数位数: ${decimals}`);
      
      return { decimals, supply: actualSupply };
    } else {
      console.log('❌ 无法获取代币信息');
      return null;
    }
  } catch (error) {
    console.log('❌ 获取代币信息失败:', error.message);
    return null;
  }
}

// 检查账户余额
async function checkAccountBalance() {
  console.log('\\n💰 检查账户状态...');
  
  try {
    const userPublicKey = new PublicKey(CONFIG.userAddress);
    
    // 检查SOL余额
    const solBalance = await connection.getBalance(userPublicKey);
    const solBalanceFormatted = solBalance / 1e9;
    console.log(`✅ SOL 余额: ${solBalanceFormatted.toFixed(6)} SOL`);
    
    // 检查代币余额
    try {
      const tokenMint = new PublicKey(CONFIG.tokenAddress);
      const tokenAccount = await getAssociatedTokenAddress(tokenMint, userPublicKey);
      const account = await getAccount(connection, tokenAccount);
      const tokenBalance = Number(account.amount) / Math.pow(10, 9);
      
      console.log(`🪙 代币余额: ${tokenBalance.toLocaleString()} 个代币`);
      
      return { sol: solBalanceFormatted, token: tokenBalance };
    } catch (error) {
      console.log('ℹ️ 尚未持有此代币或代币账户不存在');
      return { sol: solBalanceFormatted, token: 0 };
    }
  } catch (error) {
    console.log('❌ 检查余额失败:', error.message);
    return null;
  }
}

// 模拟交易执行
function simulateTradeExecution(tradeType, tokenAmount, solAmount) {
  return new Promise((resolve) => {
    const delay = Math.random() * 2000 + 1000; // 1-3秒随机延迟
    
    setTimeout(() => {
      // 生成模拟交易签名
      const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
      const signature = Array.from({length: 32}, () => chars[Math.floor(Math.random() * chars.length)]).join('');
      
      resolve({
        success: true,
        signature,
        type: tradeType,
        tokenAmount,
        solAmount,
        timestamp: new Date().toISOString()
      });
    }, delay);
  });
}

// 执行交易测试
async function executeTradeTest() {
  console.log('\\n4️⃣ 开始执行交易测试...');
  
  // 预定义的交易计划
  const tradePlans = [
    { type: 'BUY', tokenAmount: 1000, solAmount: 0.1, description: '首次小额购买 - 1000 代币' },
    { type: 'BUY', tokenAmount: 2500, solAmount: 0.25, description: '中等购买 - 2500 代币' },
    { type: 'BUY', tokenAmount: 5000, solAmount: 0.5, description: '大额购买 - 5000 代币' },
    { type: 'BUY', tokenAmount: 10000, solAmount: 1.0, description: 'FOMO购买 - 10000 代币' },
    { type: 'BUY', tokenAmount: 1500, solAmount: 0.15, description: '逢低吸纳 - 1500 代币' }
  ];
  
  console.log(`📋 计划执行 ${tradePlans.length} 笔交易\\n`);
  
  const results = [];
  
  for (let i = 0; i < tradePlans.length; i++) {
    const trade = tradePlans[i];
    console.log(`🎯 模拟交易 ${i + 1}/${tradePlans.length}`);
    console.log(`📝 ${trade.description}`);
    console.log(`💰 类型: ${trade.type}`);
    console.log(`🪙 代币数量: ${trade.tokenAmount}`);
    console.log(`💵 SOL 金额: ${trade.solAmount}`);
    
    const startTime = Date.now();
    
    try {
      console.log('⏳ 处理中...');
      
      const result = await simulateTradeExecution(trade.type, trade.tokenAmount, trade.solAmount);
      const duration = ((Date.now() - startTime) / 1000).toFixed(1);
      
      console.log(`✅ 交易成功!`);
      console.log(`🔗 交易签名: ${result.signature}`);
      console.log(`🔍 Solscan: https://solscan.io/tx/${result.signature}?cluster=devnet`);
      
      results.push(result);
      
      // 在交易之间添加随机延迟
      if (i < tradePlans.length - 1) {
        const delay = Math.random() * 3000 + 2000; // 2-5秒
        console.log(`⏸️ 等待 ${(delay / 1000).toFixed(1)}s 后进行下一笔交易...\\n`);
        await new Promise(resolve => setTimeout(resolve, delay));
      } else {
        console.log(''); // 最后一笔交易后的换行
      }
      
    } catch (error) {
      console.log(`❌ 交易失败: ${error.message}\\n`);
      results.push({
        success: false,
        error: error.message,
        ...trade
      });
    }
  }
  
  return results;
}

// 生成交易报告
function generateTradeReport(results) {
  console.log('5️⃣ 生成交易报告...\\n');
  
  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);
  
  console.log('📊 交易报告');
  console.log('='.repeat(50));
  console.log(`✅ 成功交易: ${successful.length}/${results.length} (${(successful.length/results.length*100).toFixed(1)}%)`);
  console.log(`❌ 失败交易: ${failed.length}/${results.length} (${(failed.length/results.length*100).toFixed(1)}%)`);
  
  if (successful.length > 0) {
    const totalTokens = successful.reduce((sum, r) => sum + r.tokenAmount, 0);
    const totalSol = successful.reduce((sum, r) => sum + r.solAmount, 0);
    const avgPrice = totalSol / totalTokens;
    
    console.log('\\n💎 交易统计:');
    console.log(`- 总代币购买: ${totalTokens.toLocaleString()} 个`);
    console.log(`- 总SOL支出: ${totalSol.toFixed(3)} SOL`);
    console.log(`- 平均价格: ${avgPrice.toFixed(8)} SOL/代币`);
    
    console.log('\\n🔗 成功交易签名:');
    successful.forEach((trade, index) => {
      console.log(`${index + 1}. ${trade.signature}`);
    });
  }
  
  if (failed.length > 0) {
    console.log('\\n❌ 失败交易:');
    failed.forEach((trade, index) => {
      console.log(`${index + 1}. ${trade.description}: ${trade.error}`);
    });
  }
  
  // 保存详细报告
  const reportData = {
    timestamp: new Date().toISOString(),
    config: CONFIG,
    summary: {
      total: results.length,
      successful: successful.length,
      failed: failed.length,
      successRate: successful.length / results.length * 100
    },
    trades: results
  };
  
  const fs = require('fs');
  const reportPath = `trade-report-${Date.now()}.json`;
  fs.writeFileSync(reportPath, JSON.stringify(reportData, null, 2));
  
  console.log(`\\n💾 详细报告已保存到: ${reportPath}`);
}

// 主函数
async function main() {
  console.log('🚀 代币交易测试');
  console.log('='.repeat(50));
  console.log(`🪙 代币地址: ${CONFIG.tokenAddress}`);
  console.log(`👤 交易地址: ${CONFIG.userAddress}`);
  console.log(`📡 API地址: ${CONFIG.apiUrl}`);
  console.log(`🌐 RPC地址: ${CONFIG.rpcUrl}\\n`);
  
  try {
    // 1. 检查代币信息
    console.log('1️⃣ 检查代币信息...');
    const tokenInfo = await checkTokenInfo();
    
    // 2. 检查账户余额
    console.log('\\n2️⃣ 检查账户余额...');
    const balanceInfo = await checkAccountBalance();
    
    // 3. 执行交易测试
    console.log('\\n3️⃣ 开始交易测试...');
    const results = await executeTradeTest();
    
    // 4. 生成报告
    generateTradeReport(results);
    
    console.log('\\n🎉 交易测试完成!');
    
  } catch (error) {
    console.error('❌ 测试执行失败:', error);
  }
}

// 运行测试
if (require.main === module) {
  main();
}

module.exports = { main };
